package com.bora_bandeco;

import java.io.ByteArrayOutputStream;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.FragmentManager;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.actionbarsherlock.app.ActionBar;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class RegistroActivity extends SlidingFragmentActivity {
	private static final int SELECT_PHOTO = 100;
	
	public FragmentManager mFragmentManager;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mFragmentManager = getSupportFragmentManager();

		ActionBar actionBar = this.getSupportActionBar();
		actionBar.setCustomView(R.layout.actionbar);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setLogo(R.drawable.actionbar_logo);
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayHomeAsUpEnabled(false);
        actionBar.setHomeButtonEnabled(true);

        SlidingMenu slidingMenu = getSlidingMenu();
        slidingMenu.setBehindWidthRes(R.dimen.sliding_menu_width);
        slidingMenu.setBehindScrollScale(0.0f);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        setBehindContentView(R.layout.fragment_menu);
        
        
        setContentView(R.layout.activity_registro);
        getSupportFragmentManager().beginTransaction().replace(R.id.frag_menu, new MenuFragment()).commit();
        
        // Se foram recebidos extras para essa activity exibe os valores
        Intent i = getIntent();
        
        if (i.hasExtra("nome") && i.hasExtra("numeroTelefone") && i.hasExtra("fotoCodificada")) {
        	String nome = i.getStringExtra("nome");
            String fotoCodificada = i.getStringExtra("fotoCodificada");
            String numeroTelefone = i.getStringExtra("numeroTelefone");
            
            EditText editNome = (EditText) findViewById(R.id.ed_nome);
            editNome.setText(nome);
            
            EditText editNumeroTelefone = (EditText) findViewById(R.id.ed_numero_telefone);
            editNumeroTelefone.setText(numeroTelefone);
            
            if (!fotoCodificada.equals("")) {
            	ImageView foto = (ImageView) findViewById(R.id.foto);
            	byte[] decodedString = Base64.decode(fotoCodificada, Base64.DEFAULT);
            	Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
            	foto.setImageBitmap(bitmap);
            }
        }
        
        //Esconde o ícone de notificação
        ImageView notification_icon = (ImageView)actionBar.getCustomView().findViewById(R.id.notification);
        notification_icon.setVisibility(View.GONE);
        
        //Ao clicar no ícone de foto de perfil abrir 
        //a galeria de imagens para procurar uma foto
        ImageView foto = (ImageView) findViewById(R.id.foto);
        foto.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
				photoPickerIntent.setType("image/*");
				startActivityForResult(photoPickerIntent, SELECT_PHOTO);  
			}
        });
        
        
        //Ao clicar no botão de confirmação realiza as validações e 
        //registra o usuário no servidor do aplicativo e do Google
        Button confirmar = (Button) findViewById(R.id.confirmar);
        confirmar.setOnClickListener(new View.OnClickListener() {
             
            @Override
            public void onClick(View arg0) {
            	EditText editNome = (EditText) findViewById(R.id.ed_nome);
                String nome = editNome.getText().toString();
                
                EditText editNumeroTelefone = (EditText) findViewById(R.id.ed_numero_telefone);
                String numeroTelefone = editNumeroTelefone.getText().toString();
                 
                // Checa se o usuário preencheu o nome e número de telefone (campos obrigatórios)
                if (nome.trim().length() > 0 && numeroTelefone.length() > 0) {
                	//Se foi selecionada alguma foto para o perfil codifica-a e envia como string
                	ImageView imageView = (ImageView) findViewById(R.id.foto);
                	String fotoCodificada = "";
                	
                	if (imageView.getTag() != null &&
            			((Integer)imageView.getTag()).intValue() == SELECT_PHOTO) {
                		ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    	Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
                    	bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    	byte[] imageBytes = baos.toByteArray();
                    	fotoCodificada = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                	}
                	
                    // Envia as informações para CardapioActivity onde é feita 
                	// a chamada assíncrona e o registro do usuário 
                	Intent i = new Intent(getApplicationContext(), CardapioActivity.class);
                	i.putExtra("nome", nome);
                    i.putExtra("fotoCodificada", fotoCodificada);
                    i.putExtra("numeroTelefone", numeroTelefone);
                    startActivity(i);
                    
                    finish();
                } else {
                	int duration = Toast.LENGTH_LONG;
                	
            		//Os dados não foram preenchidos, faz-se notificação
                	Toast toast = Toast.makeText(RegistroActivity.this, R.string.erro_campos_nao_preenchidos, duration);
        			toast.show();
                }
            }
        });
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 

        switch (requestCode) { 
        	case SELECT_PHOTO:
	            if (resultCode == RESULT_OK){  
	            	Uri selectedImage = imageReturnedIntent.getData();
	                String[] filePathColumn = {MediaColumns.DATA};

	                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	                cursor.moveToFirst();

	                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	                String filePath = cursor.getString(columnIndex);
	                cursor.close();

	                Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
	                
	                yourSelectedImage = this.scaleCenterCrop(yourSelectedImage, 96, 96);
	                
	                ImageView foto = (ImageView) findViewById(R.id.foto);
	                foto.setImageBitmap(yourSelectedImage);
	                
	                foto.setTag(SELECT_PHOTO);
	            }
            break;
        }
    }
    
    public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
        int sourceWidth = source.getWidth();
        int sourceHeight = source.getHeight();

        // Compute the scaling factors to fit the new height and width, respectively.
        // To cover the final image, the final scaling will be the bigger 
        // of these two.
        float xScale = (float) newWidth / sourceWidth;
        float yScale = (float) newHeight / sourceHeight;
        float scale = Math.max(xScale, yScale);

        // Now get the size of the source bitmap when scaled
        float scaledWidth = scale * sourceWidth;
        float scaledHeight = scale * sourceHeight;

        // Let's find out the upper left coordinates if the scaled bitmap
        // should be centered in the new size give by the parameters
        float left = (newWidth - scaledWidth) / 2;
        float top = (newHeight - scaledHeight) / 2;

        // The target rectangle for the new, scaled version of the source bitmap will now
        // be
        RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

        // Finally, we create a new bitmap of the specified size and draw our new,
        // scaled bitmap onto it.
        Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
        Canvas canvas = new Canvas(dest);
        canvas.drawBitmap(source, null, targetRect, null);

        return dest;
    }
}
